package com.hz.friends.fragment;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.BufferType;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.GetCallback;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.hz.friends.activity.MaintabsActivity;
import com.hz.friends.activity.R;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.chat.GroupChatActivity;
import com.hz.friends.chat.SmileUtils;
import com.hz.friends.chat.Helper.CCPIntentUtils;
import com.hz.friends.chat.entity.IMChatMessage;
import com.hz.friends.db.DBContactUser;
import com.hz.friends.db.DBMessageManager;
import com.hz.friends.global.Global;
import com.hz.friends.location.LocationService;
import com.hz.friends.serverrequest.ALCCPEngine;
import com.hz.friends.serverrequest.ALCCPEngine.ALMessageOfChatType;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.UtilTools;

public class MessageFragment extends BaseFragment {
	private PullToRefreshListView mlistview;
	private MessageAdpter madpter;
	private int pageindex = 0;
	private Handler mhandler = new Handler();
	private MessageReciverBroad messageReciverBroad;
	private DBMessageManager dbmanager;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_message, null);
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		init();
		initViews();
		setViews();
		initEvents();
		queryData();
	}

	@Override
	protected void init() {
		messageReciverBroad = new MessageReciverBroad();
		// 实例化过滤器并设置要过滤的广播
		IntentFilter intentFilter = new IntentFilter(
				CCPIntentUtils.INTENT_FRAGMENT_MESSAGE_UPDATE);
		intentFilter.addAction(CCPIntentUtils.INTENT_IM_SAVE_DB);
		intentFilter.addAction(CCPIntentUtils.INTENT_IM_RECIVE);
		intentFilter.addAction(CCPIntentUtils.INTENT_IM_SAVE_AND_SENT);
		// 注册广播
		getActivity().registerReceiver(messageReciverBroad, intentFilter);
		dbmanager = new DBMessageManager(getActivity());
	}

	@Override
	protected void initViews() {
		mlistview = (PullToRefreshListView) findViewById(R.id.mlistview);
		ImageButton imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left);
		ImageButton imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right);
		TextView imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title);
		imbtn_bar_left.setVisibility(View.INVISIBLE);
		imbtn_bar_right.setVisibility(View.INVISIBLE);
		imbtn_bar_title.setText("Message");
		mlistview.getRefreshableView().setFooterDividersEnabled(true);
	}

	@Override
	protected void setViews() {
		madpter = new MessageAdpter(getActivity());
		mlistview.setAdapter(madpter);
	}

	private void queryData() {
		if (getActivity() == null) {
			mhandler.post(new Runnable() {

				@Override
				public void run() {
					mlistview.onRefreshComplete();
				}
			});
			return;
		}
		List<DBContactUser> userlist = dbmanager.queryUserList(pageindex);
		mhandler.post(new Runnable() {

			@Override
			public void run() {
				mlistview.onRefreshComplete();
			}
		});

		madpter.addData(userlist);
		madpter.notifyDataSetChanged();
		pageindex++;

		int unreadmessageconut = dbmanager.getUnReadMessagesCount();
		((MaintabsActivity) getActivity())
				.setMessageBubbleCount(unreadmessageconut);
	}

	@Override
	protected void initEvents() {
		mlistview.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				queryData();
			}

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				madpter.clear();
				pageindex = 0;
				queryData();
			}
		});

		mlistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 0)
					return;
				try {
					AVUser user = (AVUser) AVUser.createWithoutData(
							AVUser.class, madpter.getItem(position - 1)
									.getUserid());
					user.fetchIfNeededInBackground(new GetCallback<AVObject>() {

						@Override
						public void done(AVObject arg0, AVException arg1) {
							if (arg0 != null && arg1 == null) {
								if (getActivity() == null)
									return;
								CustomApplication.getInstance().user = (AVUser) arg0;
								Intent intent = new Intent(getActivity(),
										GroupChatActivity.class);
								intent.putExtra("titlename", CustomApplication
										.getInstance().user
										.getString("nickname"));
								intent.putExtra("isGroup", false);
								getActivity().startActivity(intent);
							}
							if (arg1 != null)
								arg1.printStackTrace();
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
	}

	@Override
	public void initDatas() {
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(messageReciverBroad);
		if (dbmanager != null)
			dbmanager.closeDB();
	}

	// 监听消息变化
	class MessageReciverBroad extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(
					CCPIntentUtils.INTENT_FRAGMENT_MESSAGE_UPDATE)
					|| intent.getAction().equals(
							CCPIntentUtils.INTENT_IM_RECIVE)) {
				madpter.clear();
				pageindex = 0;
				queryData();
			} else if (intent.getAction().equals(
					CCPIntentUtils.INTENT_IM_SAVE_DB)) {// 保存消息
				IMChatMessage message = (IMChatMessage) intent
						.getSerializableExtra("IMChatMessage");
				if (message != null) {
					dbmanager.save(message);
					dbmanager.saveOrUpdate(message.getFromuser());
				}

			} else if (intent.getAction().equals(
					CCPIntentUtils.INTENT_IM_SAVE_AND_SENT)) {// 接受到消息保存数据库并通知页面
                String msgid = intent.getStringExtra("msgObjId");
                saveMessage(msgid);
			}

		}
	}

	/**
	 * 保存接受到个人聊天消息，并过滤掉本地已有的
	 * 
	 * @param msgId
	 *            消息id
	 */
	private void saveMessage(final String msgId) {
		if(TextUtils.isEmpty(msgId))
			return;
		boolean isexist = dbmanager.queryMessagesById(msgId);
		if (isexist)// 本地存在该消息
			return;
		AVObject msgobj = AVObject.createWithoutData("MessageOfChat", msgId);
		// 下载消息
		msgobj.fetchIfNeededInBackground("fromUser,toUser",
				new GetCallback<AVObject>() {
					@Override
					public void done(AVObject moc, AVException e) {
						if (moc != null && e == null) {
							/*
							 * 加入本地聊天记录
							 */
							IMChatMessage chatmessage = null;
							try {
								String objid = moc.getObjectId();
								AVUser fromuser = moc.getAVUser("fromUser");
								org.json.JSONObject json = moc
										.getJSONObject("userData");
								int type = json.getInt("type");
								String url = json.getString("url");
								if (type == ALMessageOfChatType.ALMessageOfChatTypeOfText
										.get_value()) {// 文本
									chatmessage = new IMChatMessage();
									chatmessage.setMessageContent(url);
									chatmessage
											.setMessageDirection(IMChatMessage.MessageDirect.RECEIVE);
									chatmessage
											.setMessageType(IMChatMessage.MessageType.TXT);
									chatmessage.setMessagetime(moc
											.getCreatedAt());
									chatmessage.setMessageId(objid);
									chatmessage.setFromuser(new DBContactUser(
											fromuser, url, chatmessage
													.getMessagetime()));

								} else if (type == ALMessageOfChatType.ALMessageOfChatTypeOfVoice // 语音
										.get_value()) {
									int voiceduration = json.getInt("duration");
									chatmessage = new IMChatMessage();
									chatmessage
											.setMessageDirection(IMChatMessage.MessageDirect.RECEIVE);
									chatmessage
											.setMessageType(IMChatMessage.MessageType.VOICE);
									chatmessage.setMessagetime(moc
											.getCreatedAt());
									chatmessage.setMessageId(objid);
									chatmessage.setFromuser(new DBContactUser(
											fromuser, "[语音]", chatmessage
													.getMessagetime()));
									chatmessage.setMediaUrl(url);
									chatmessage.setMediaduration(voiceduration);
									// 判断本地文件
									String voicename = url.substring(
											url.lastIndexOf("/" + 1),
											url.length());
									final String voicefilepath = Environment
											.getExternalStorageDirectory()
											+ "/"
											+ Global.productName
											+ "/voice/" + voicename;
									File voicefile = UtilTools
											.createFile(voicefilepath);
									if (voicefile != null
											&& voicefile.length() > 0) {// 文件存在文件包含内容
										chatmessage.setMediaPath(voicefilepath);
									}
								} else if (type == ALMessageOfChatType.ALMessageOfChatTypeOfImage// 图片
										.get_value()) {

									chatmessage = new IMChatMessage();
									// 设置宽高
									String imagesizes = json.getString("size");
									if (!TextUtils.isEmpty(imagesizes)
											&& imagesizes.length() > 2) {
										String[] sizesarr = imagesizes
												.substring(1,
														imagesizes.length() - 1)
												.split(",");
										if (sizesarr != null
												&& sizesarr.length == 2) {
											chatmessage.setImageWidth(Integer
													.parseInt(sizesarr[0]));
											chatmessage.setImageHeight(Integer
													.parseInt(sizesarr[1]));
										}
									}
									chatmessage
											.setMessageDirection(IMChatMessage.MessageDirect.RECEIVE);
									chatmessage
											.setMessageType(IMChatMessage.MessageType.IMAGE);
									chatmessage.setMessagetime(moc
											.getCreatedAt());
									chatmessage.setMessageId(objid);
									chatmessage.setFromuser(new DBContactUser(
											fromuser, "[图片]", chatmessage
													.getMessagetime()));
									chatmessage.setMediaUrl(url);

								} else if (type == ALMessageOfChatType.ALMessageOfChatTypeOfVideo // 视频
										.get_value()) {
									chatmessage = new IMChatMessage();
									chatmessage
											.setMessageDirection(IMChatMessage.MessageDirect.RECEIVE);
									chatmessage
											.setMessageType(IMChatMessage.MessageType.VIDEO);
									chatmessage.setMessagetime(moc
											.getCreatedAt());
									chatmessage.setMessageId(objid);
									chatmessage.setFromuser(new DBContactUser(
											fromuser, "[视频]", chatmessage
													.getMessagetime()));
									chatmessage.setMediaUrl(url);
								} else if (type == ALMessageOfChatType.ALMessageOfChatTypeOfGroupInvite // 群邀请
										.get_value()) {
									chatmessage = new IMChatMessage();
									chatmessage
											.setMessageDirection(IMChatMessage.MessageDirect.RECEIVE);
									chatmessage
											.setMessageType(IMChatMessage.MessageType.GROUPINVITE);
									chatmessage.setMessagetime(moc
											.getCreatedAt());
									chatmessage.setMessageId(objid);
									chatmessage.setMessageContent(json
											.getString("message"));
									chatmessage.setMediaUrl(url); // 把群对象id保存
									chatmessage.setFromuser(new DBContactUser(
											fromuser, "[群邀请]", chatmessage
													.getMessagetime()));
								}

							} catch (Exception e2) {
								e2.printStackTrace();
							}

							if (chatmessage != null) {// 通知页面更新
								dbmanager.save(chatmessage);
								dbmanager.saveOrUpdate(chatmessage
										.getFromuser());
								Intent intent = new Intent(
										CCPIntentUtils.INTENT_IM_RECIVE);
								intent.putExtra("IMChatMessage", chatmessage);
								intent.putExtra("isGroup", false);
								intent.putExtra("msgObjId", msgId);
								CustomApplication.getInstance().sendBroadcast(
										intent);
							}

						}
					}
				});
	}

	class MessageAdpter extends BaseAdapter {
		private List<DBContactUser> datas = new ArrayList<DBContactUser>();
		private Context context;
		private AQuery aq;

		@Override
		public int getCount() {
			return datas.size();
		}

		public MessageAdpter(Context context) {
			this.context = context;
			aq = new AQuery(context);
		}

		@Override
		public DBContactUser getItem(int position) {
			return datas.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public void addData(List<DBContactUser> datas) {
			this.datas.addAll(datas);
		}

		public void clear() {
			this.datas.clear();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = LayoutInflater.from(getActivity()).inflate(
					R.layout.adpter_fragment_message, null);
			Button btn_bubble = (Button) view.findViewById(R.id.btn_bubble); // 小红点
			final ImageView imv_heard = (ImageView) view
					.findViewById(R.id.imv_heard); // 小红点
			TextView txv_name = (TextView) view.findViewById(R.id.txv_name); // 小红点
			TextView txv_content = (TextView) view
					.findViewById(R.id.txv_content); // 小红点
			TextView txv_time = (TextView) view.findViewById(R.id.txv_time); // 小红点

			// 设置小圆点
			Bitmap redbitmap = BitmapUtils.drawCycleImage("#ff4948",
					getResources().getDimensionPixelSize(R.dimen.mes_bubble));
			int strokwidth = DensityUtil.dip2px(getActivity(), 1);
			int width = getResources()
					.getDimensionPixelSize(R.dimen.mes_bubble) + strokwidth;
			Bitmap redbitmap2 = BitmapUtils.getCircleStrokbitmap(getActivity(),
					redbitmap, width, strokwidth, "#ffffff");
			btn_bubble.setBackgroundDrawable(new BitmapDrawable(redbitmap2));

			DBContactUser user = datas.get(position);
			txv_name.setText(user.getNickname());
			Spannable span = SmileUtils.getSmiledText(context,
					user.getLastContent());
			txv_content.setText(span, BufferType.SPANNABLE);
			setTime(txv_time, user.getTime());
			// 头像
			// default image
			final int heardwidth = context.getResources()
					.getDimensionPixelSize(R.dimen.mes_heard);
			Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5",
					heardwidth);
			Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(
					context, crclebitmap, heardwidth, 1, "#eeeeee");
			imv_heard.setImageBitmap(crclestrokebitmap);

			aq.id(imv_heard).image(user.getHeardurl(), true, true, heardwidth,
					0, new BitmapAjaxCallback() {
						@Override
						protected void callback(String url, ImageView iv,
								Bitmap bm, AjaxStatus status) {
							super.callback(url, iv, bm, status);
							Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(
									context, bm, heardwidth, 1, "#eeeeee");
							imv_heard.setImageBitmap(mbitmap);
						}
					});
			// 查询未读数
			int count = dbmanager.getMessagesCountByFromUserId(
					user.getUserid(), IMChatMessage.STATE_UNREAD);
			if (count > 0) {
				btn_bubble.setVisibility(View.VISIBLE);
				btn_bubble.setText(String.valueOf(count));
			} else {
				btn_bubble.setVisibility(View.INVISIBLE);
			}
			return view;
		}

		private void setTime(TextView txv, Date date) {
			Calendar mcal = Calendar.getInstance();
			Calendar cal = Calendar.getInstance();
			SimpleDateFormat spf1 = new SimpleDateFormat("MM.dd");
			SimpleDateFormat spf2 = new SimpleDateFormat("hh:mm");
			mcal.setTime(date);
			// 同一天
			if ((mcal.get(Calendar.YEAR) == cal.get(Calendar.YEAR))
					&& (mcal.get(Calendar.MONTH) == cal.get(Calendar.MONTH))
					&& (mcal.get(Calendar.DAY_OF_MONTH) == cal
							.get(Calendar.DAY_OF_MONTH))) {
				txv.setText(spf2.format(date));
			} else {
				txv.setText(spf1.format(date));
			}

		}

	}
}
